<template>
  <view class="page">
    <view class="container">
      <!-- 顶部返回按钮 -->
      <view class="back-btn" @click="uni.navigateBack()">
        <image class="back-icon" src="@/static/icons/pageReturn.svg" mode="aspectFit"></image>
      </view>

      <!-- 标题 -->
      <view class="title">忘记密码</view>

      <!-- 输入框区域 -->
      <view class="input-area">
        <input
            type="text"
            class="input-field"
            placeholder="+86 请输入手机号"
            v-model="formData.phone"
        />

        <input
            type="text"
            class="input-field"
            placeholder="请输入验证码"
            v-model="formData.code"
        />
        
        <view class="send-code-container">
          <button 
            class="send-code-btn" 
            :disabled="isSendingCode || !!countdown"
            @click="sendVerificationCode"
          >
            {{ countdown ? `${countdown}s后重新发送` : '获取验证码' }}
          </button>
        </view>

        <!-- 密码输入框 -->
        <view class="password-input">
          <input
              type="text"
              class="input-field"
              placeholder="请输入新密码(至少6位)"
              v-model="displayPassword"
              @input="handlePasswordInput"
          />
          <view class="eye-icon-button" @tap="togglePasswordVisibility">
            <view class="eye-icon-inner">
              <image
                  class="eye-icon"
                  :src="showPassword ? '/static/icons/eye_open.svg' : '/static/icons/eye_close.svg'"
                  mode="aspectFit"
              ></image>
            </view>
          </view>
        </view>

        <!-- 确认密码输入框 -->
        <view class="password-input">
          <input
              type="text"
              class="input-field"
              placeholder="请再次输入新密码"
              v-model="displayConfirmPassword"
              @input="handleConfirmPasswordInput"
          />
          <view class="eye-icon-button" @tap="toggleConfirmPasswordVisibility">
            <view class="eye-icon-inner">
              <image
                  class="eye-icon"
                  :src="showConfirmPassword ? '/static/icons/eye_open.svg' : '/static/icons/eye_close.svg'"
                  mode="aspectFit"
              ></image>
            </view>
          </view>
        </view>

        <button
            class="submit-btn"
            :class="{ active: canSubmit }"
            :disabled="!canSubmit"
            @click="handleSubmit"
        >
          确认修改
        </button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, watch } from 'vue';
import userApi from '@/http/models/user';

const showPassword = ref(false);
const showConfirmPassword = ref(false);
const isSendingCode = ref(false);
const countdown = ref(0);
let countdownTimer = null;

// 实际密码存储
const realPassword = ref('');
const realConfirmPassword = ref('');

// 显示用密码
const displayPassword = ref('');
const displayConfirmPassword = ref('');

// 表单数据
const formData = ref({
  phone: '',
  code: '',
  password: '',
  confirmPassword: ''
});

// 监听真实密码变化，更新显示密码
watch(realPassword, (newVal) => {
  if (showPassword.value) {
    displayPassword.value = newVal; // 显示真实密码
  } else {
    displayPassword.value = '*'.repeat(newVal.length); // 显示*号
  }
});

// 监听真实确认密码变化，更新显示密码
watch(realConfirmPassword, (newVal) => {
  if (showConfirmPassword.value) {
    displayConfirmPassword.value = newVal; // 显示真实密码
  } else {
    displayConfirmPassword.value = '*'.repeat(newVal.length); // 显示*号
  }
});

// 处理密码输入
const handlePasswordInput = () => {
  if (showPassword.value) {
    // 如果显示真实密码，用户输入的是真实密码
    realPassword.value = displayPassword.value;
  } else {
    // 如果显示*号，根据输入长度更新真实密码
    const inputLength = displayPassword.value.length;
    const currentLength = realPassword.value.length;

    if (inputLength > currentLength) {
      // 用户输入了新字符
      realPassword.value += displayPassword.value.slice(-1);
    } else if (inputLength < currentLength) {
      // 用户删除了字符
      realPassword.value = realPassword.value.slice(0, -1);
    }
  }
  formData.value.password = realPassword.value;
};

// 处理确认密码输入
const handleConfirmPasswordInput = () => {
  if (showConfirmPassword.value) {
    realConfirmPassword.value = displayConfirmPassword.value;
  } else {
    const inputLength = displayConfirmPassword.value.length;
    const currentLength = realConfirmPassword.value.length;

    if (inputLength > currentLength) {
      realConfirmPassword.value += displayConfirmPassword.value.slice(-1);
    } else if (inputLength < currentLength) {
      realConfirmPassword.value = realConfirmPassword.value.slice(0, -1);
    }
  }
  formData.value.confirmPassword = realConfirmPassword.value;
};

// 切换密码可见性
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value;

  if (showPassword.value) {
    // 显示真实密码
    displayPassword.value = realPassword.value;
  } else {
    // 显示*号
    displayPassword.value = '*'.repeat(realPassword.value.length);
  }
};

// 切换确认密码可见性
const toggleConfirmPasswordVisibility = () => {
  showConfirmPassword.value = !showConfirmPassword.value;

  if (showConfirmPassword.value) {
    displayConfirmPassword.value = realConfirmPassword.value;
  } else {
    displayConfirmPassword.value = '*'.repeat(realConfirmPassword.value.length);
  }
};

// 计算属性：手机号是否有效
const isPhoneValid = computed(() => {
  return /^1[3-9]\d{9}$/.test(formData.value.phone);
});

// 计算属性：是否可以提交表单
const canSubmit = computed(() => {
  return (
      isPhoneValid.value &&
      formData.value.code.trim() !== '' &&
      realPassword.value.length >= 6 &&
      realPassword.value === realConfirmPassword.value
  );
});

// 发送验证码
const sendVerificationCode = async () => {
  if (!isPhoneValid.value) {
    uni.showToast({ title: '请输入正确的手机号', icon: 'none' });
    return;
  }

  if (isSendingCode.value) return;

  isSendingCode.value = true;
  
  try {
    // 这里应该调用实际的发送验证码接口
    // 模拟发送验证码过程
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    // 开始倒计时
    startCountdown();
    
    uni.showToast({ title: '验证码已发送', icon: 'success' });
  } catch (error) {
    console.error('发送验证码失败:', error);
    uni.showToast({ title: '发送验证码失败，请稍后重试', icon: 'none' });
  } finally {
    isSendingCode.value = false;
  }
};

// 开始倒计时
const startCountdown = () => {
  countdown.value = 60;
  countdownTimer = setInterval(() => {
    countdown.value--;
    if (countdown.value <= 0) {
      clearInterval(countdownTimer);
      countdownTimer = null;
    }
  }, 1000);
};

// 处理提交
const handleSubmit = async () => {
  if (!canSubmit.value) return;

  try {
    // 这里应该调用实际的重置密码接口
    // 模拟重置密码过程
    await new Promise(resolve => setTimeout(resolve, 1000));
    
    uni.showToast({ title: '密码重置成功', icon: 'success' });
    
    // 返回登录页面
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  } catch (error) {
    console.error('重置密码失败:', error);
    uni.showToast({ title: '重置密码失败，请稍后重试', icon: 'none' });
  }
};

// 组件销毁时清除定时器
// 注意：在实际项目中可能需要根据具体框架调整清理方式
</script>

<style scoped>
@import '../../components/scss/login-common.css';

.send-code-container {
  width: 100%;
  margin-bottom: 20px;
}

.send-code-btn {
  width: 100%;
  height: 50px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 12px;
  color: white;
  font-weight: 600;
  font-size: 16px;
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
}

.send-code-btn:disabled {
  opacity: 0.7;
  cursor: not-allowed;
}
</style>